package cn.cjxy.springmvcdemo1.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.UUID;

/**
 * @author huangjie
 * @date 2025/10/9
 */
@RequestMapping("/file")
@Controller
public class FileController {

    @RequestMapping(value = "/up",method = RequestMethod.POST)
    public String uploadFile(MultipartFile fileUpload, String username, HttpServletRequest req) throws FileNotFoundException, IOException {
        req.setCharacterEncoding("UTF-8");
        System.out.println("普通表单获取方式：" + username);

        //上传表单信息：注意MultipartFile对象的名称必须与上传表单项的name属性值一致
        System.out.println("上传文件是否为空:" + fileUpload.isEmpty());
        System.out.println("上传文件的大小（字节）:" + fileUpload.getSize());
        System.out.println("上传文件的类型:" + fileUpload.getContentType());
        System.out.println("上传表单name属性值:" + fileUpload.getName());
        System.out.println("上传文件名:" + fileUpload.getOriginalFilename());

        // 获取upload真实路径:一大巨坑（uploadFile千万不要和请求upload一样的名字，否则第二次上传出现405）
        String realPath = req.getServletContext().getRealPath("/uploadFile");
        System.out.println(realPath);
        File file = new File(realPath);
        if (!file.exists()) {// 如果upload文件夹不存在，就创建
            file.mkdirs();
        }

        String prefix = UUID.randomUUID().toString().replaceAll("-", "");
//使用UUID加前缀命名文件，防止名字重复被覆盖
        String fileName = prefix+"_"+fileUpload.getOriginalFilename();

        InputStream in= fileUpload.getInputStream();;//声明输入输出流
        OutputStream out=new FileOutputStream(new File(realPath+"\\"+fileName));//指定输出流的位置;

        //使用IOUtils.copy实现文件复制
        IOUtils.copy(in,out);
        System.out.println("上传成功");
        in.close();
        out.close();
        return "redirect:/fileup.jsp";
    }


}
